require "View/MainUI/UICity"
require "proto/chat/message/ReqChatServiceInfoMessage"
require "proto/chat/message/ReqChatInfoMessage"
chatHandler = chatHandler or {};
G.serverData = G.serverData or {};
local this = chatHandler

local sub_type = Config.sub_type_chat
chatHandler.mychatChannel = {};
chatHandler.MyCityChan="";
chatHandler.MyAreaChanel="";
chatHandler.MyAreaChanelChoose="";
chatHandler.NowbroadCastCh="";
local orderId = 1;



-------------------------------
---请求聊天token
function this.ReqChatServiceInfo()
    if IsWindowEditor() then return end
    SDKManager.logError("[IM]ReqChatServiceInfo")
    local _req = ReqChatServiceInfoMessage.New()
    sendReqMessage(_req)
end
---聊天服务房间信息
function this.ResChatServiceInfo(msg)
    if msg.state ~= 0 then
        return
    end
    MyLog('收到聊天室消息'..tostring(msg.teamBossRoom))
    SDKManager.ResChatServiceInfo(tostring(msg.appKey),tostring(msg.userToken),msg.worldRoom,msg.maincityRoom,msg.unionRoom,msg.teamBossRoom)
end
---公会房间变更通知
function this.ResUnionRoomChange(msg)
    if msg.state ~= 0 then
        return
    end
    SDKManager.ResUnionRoomChange(msg.unionRoom)
end
function this.ResInvasionRoomChange(msg)
    if msg.state ~= 0 then
        return
    end
    SDKManager.ResInvasionTeamChange(msg.teamBossRoom)
end
--发送游戏服数据
function this.ReqChatInfo(type,content,privateId)
    local m = ReqChatInfoMessage.New()
    m.type = type
    m.content = content
    m.receiverOid = privateId or 0
    sendReqMessage(m)
end

function this.ResGetUserInfo(message)
    if message.state == 0 then
        -- local _userId = tostring(message.userId)
        -- local _userName = tostring(message.userName)
        -- local _portraitUrl = tostring(message.portraitUrl)
        --SDKManager.ResGetMyselfUserInfo(tostring(message.appKey),tostring(message.userToken))
    end
end

-------------------------------

--[[function chatHandler:receivePacket( p )
	local mainType = WebMsgMgr:getMainType(p);
	local subType = WebMsgMgr:getSubType(p);
	local switch = {  
	    [sub_type.sub_sendChatMsg] = function()  
	       return chatHandler.decode_sendChat(p);
	    end,
	    [sub_type.sub_receiveChatMsg] = function()  
	       return chatHandler.decode_receiveChat(p);
	    end,
        [sub_type.sub_receiveAction] = function()
            return chatHandler.decode_receiveAction(p)
        end,
        [sub_type.sub_receiveShowItem] = function()
            return chatHandler.decode_receiveShowItem(p)
        end,
        [sub_type.sub_receiveItemList] = function()
            return chatHandler.decode_receiveItemList(p)
        end,
        [sub_type.sub_receivePersonMsg] = function()
            return chatHandler.decode_receivePersonMsg(p)
        end,
        [sub_type.sub_receivePersonNews] = function()
            return chatHandler.decode_receivePersonNews(p)
        end,
        [sub_type.sub_receiveEventMsg] = function()
            return chatHandler.decode_receiveEventMsg(p)
        end,
}

local fSwitch = switch[subType]
	  
	if fSwitch then 
	    local data = fSwitch() 
	    if data ~= nil and data.error ~= nil then		    	
			showUI(PanelNames.UISysTips,data.opt,mainType,subType);
			return;
	    end

	    --记录数据更新，刷新对应ui
		local name = getProtocol(mainType,subType);
		FireEvent(name,data); 
	end  
end

--聊天信息返回包
function chatHandler.decode_sendChat( p )
	local data = {}
	local opt = WebMsgMgr:getOpt(p);
	data["opt"] = opt;
	if opt~= 0 then
		data["tips"] = WebMsgMgr:readString(p);
		UISysTips.AddMsg(data["tips"]);
	end
end

--动作到达包
function chatHandler.decode_receiveAction(p)
    local data = {};
    data["chatAction"] = {}
    local opt = WebMsgMgr:getOpt(p);
    data["opt"] = opt;
    data["count"] = WebMsgMgr:readByte(p);
    for i = 1,data["count"] do
        local chatAction = {}
        chatAction["actId"] = WebMsgMgr:readInt(p);
        chatAction["actName"] = WebMsgMgr:readString(p);
        chatAction["channel"] = WebMsgMgr:readShort(p)
        table.insert(data["chatAction"],chatAction)
    end

    G.serverData["chatAction"] = G.serverData["chatAction"] or {};
    G.serverData["chatAction"] = data
    return data;
end
--展示物品列表到达
function chatHandler.decode_receiveItemList(p)
    local data = {}
    local opt = WebMsgMgr:getOpt(p)
    data["opt"] = opt
    data["count"] = WebMsgMgr:readByte(p)
    for i = 1,data["count"] do
        data["prefixContent"] = WebMsgMgr:readString(p)
        data["postfixContent"] = WebMsgMgr:readString(p)
    end
    return data;
end
--展示物品tips到达
function chatHandler.decode_receiveShowItem(p)
    local data = {}
    local opt = WebMsgMgr:getOpt(p);
    data["opt"] = opt;
    data["tips"] = WebMsgMgr:readString(p);
    UISysTips.AddMsg(data["tips"]);
end
--私聊离线消息通知包
function chatHandler.decode_receivePersonMsg(p)
    local data = {}
    local opt = WebMsgMgr:getOpt(p);
    data["opt"] = opt;
    data["messageCount"] = WebMsgMgr:readByte(p)
    data["personChat"] = {}
    for i = 1,data["messageCount"] do
        local personChat = {}
        personChat["Face"] = WebMsgMgr:readByte(p)
        personChat["roleId"] = WebMsgMgr:readInt(p)
        personChat["roleName"] = WebMsgMgr:readString(p)
        personChat["Message"] = WebMsgMgr:readString(p)
        personChat["color"] = WebMsgMgr:readInt(p)
        table.insert(data["personChat"],personChat)
    end
    --print("personMsg")
    --printTable(data)
    return data
end
--私聊历史消息到达
function chatHandler.decode_receivePersonNews(p)
    local data = {}
    local opt = WebMsgMgr:getOpt(p);
    data["opt"] = opt;
    data["allCount"] = WebMsgMgr:readInt(p)
    data["messageCount"] = WebMsgMgr:readByte(p)
    data["personChat"] = {}
    for i = 1,data["messageCount"] do
        local personChat = {}
        personChat["Face"] = WebMsgMgr:readByte(p)
        personChat["roleId"] = WebMsgMgr:readInt(p)
        personChat["roleName"] = WebMsgMgr:readString(p)
        personChat["Message"] = WebMsgMgr:readString(p)
        table.insert(data["personChat"],personChat)
    end
    return data
end
--
function chatHandler.decode_receiveEventMsg(p)
    local data = {}
    local opt = WebMsgMgr:getOpt(p);
    data["opt"] = opt;
    data["eventTip"] = WebMsgMgr:readString(p)
    data["rollMode"] = WebMsgMgr:readByte(p)
    data["cancelType"] = WebMsgMgr:readByte(p)
    data["confirmType"] = WebMsgMgr:readByte(p)
    data["showType"] = WebMsgMgr:readByte(p)
    data["rollCount"] = WebMsgMgr:readByte(p)
    G.serverData["EventMsg"] = G.serverData["EventMsg"] or {};
    table.insert(G.serverData["EventMsg"],1,data);
    FireEvent("EventMsg",data)
    return data
end

--聊天信息到达包
function chatHandler.decode_receiveChat(p)
    local data = {};
    local opt = WebMsgMgr:getOpt(p);
    data["opt"] = opt;
    data["Channel"] = WebMsgMgr:readByte(p);
    data["Face"] = WebMsgMgr:readByte(p);
    data["roleId"] = WebMsgMgr:readInt(p);
    data["roleName"] = WebMsgMgr:readString(p);
    data["prof"] = WebMsgMgr:readByte(p)
    data["race"] = WebMsgMgr:readByte(p)
    data["head"] = WebMsgMgr:readByte(p)
    data["Message"] = WebMsgMgr:readString(p);
    data["color"] = WebMsgMgr:readInt(p);

    G.serverData["chat"] = G.serverData["chat"] or {};
    table.insert(G.serverData["chat"],1,data);
	
	if data["Channel"] == 4 then
		FireEvent(Config.EventType.BattleChat,data);
	end
    return data;
end]]
---聊天世界频道
function chatHandler.loginWorldRoom()
    this.SetChannel(Config.MsgChannel.World,"chat-world")
    this.SetChannel(Config.MsgChannel.Server,"chat-world-"..AppConst.ServerId)
    WebSocketMgr.GetInstance():Send(chatHandler.getJoinData(this.GetChannel(Config.MsgChannel.World)));
    WebSocketMgr.GetInstance():Send(chatHandler.getJoinData(this.GetChannel(Config.MsgChannel.Server)));
end

function chatHandler.SetChannel(channel,name)
    this.mychatChannel[channel] = name
end
function chatHandler.GetChannel(channel)
    return this.mychatChannel[channel]
end

function chatHandler.getJoinData(channelid)
    local senddata = {action="join"};
    senddata.channel = channelid;
    senddata.orderId = orderId;
    orderId = orderId + 1;
    return getJsonStr(senddata);
end

function chatHandler.getLeaveData(channelid)
    local senddata = {action="quit"};
    senddata.channel = channelid;
    senddata.orderId = orderId;
    orderId = orderId + 1;
    return getJsonStr(senddata);
end


function chatHandler.resetWebSocket()
    WebSocketMgr.GetInstance():Close();
end

function chatHandler.broadCastMsg(channel,msg)

    local senddata = {action="broadcast"};
    senddata.channel = channel;
    senddata.message = msg;
    senddata.orderId = orderId;
    orderId = orderId + 1;
    WebSocketMgr.GetInstance():Send(getJsonStr(senddata));
end

function chatHandler.broadCastCityMsg(channel,msg)

    local senddata = {action="broadcast"};
    senddata.channel = channel;
    senddata.message = msg;
    senddata.orderId = orderId;
    orderId = orderId + 1;
    local jsos=getJsonStr(senddata);
    local CityStrData=string.gsub(jsos,"\\","")
    WebSocketMgr.GetInstance():Send(CityStrData);
end

function chatHandler.sendPrivateMsg(playerid,msg)
    local senddata = {action="send"};
    senddata.channel = "chat-player-"..playerid;
    senddata.message = msg;
    senddata.orderId = orderId;
    orderId = orderId + 1;
    WebSocketMgr.GetInstance():Send(getJsonStr(senddata));
end
--获得私聊离线消息
function chatHandler.sendGetPrivateOfflineMsg()
    local senddata = {action="offline"};
    senddata.channel = "chat-player-"..logicMgr.HeroManager.GetRoleId();
    WebSocketMgr.GetInstance():Send(getJsonStr(senddata));
end
--聊天服连接成功
function chatHandler.onChatConnect()
    chatHandler.loginWorldRoom();
    this.sendGetPrivateOfflineMsg()
end
local curChannel;

function chatHandler.onRecChatMsg(msg)
    local msgdata = decodeJsonStrToTabel(msg);
    if msgdata == nil then
        return;
    end
    --logError("chatHandler.onRecChatMsg:"..msg)
    --my join room
    if msgdata.parameter == "join" then
        logicMgr.LBSManager.JoinRoomSuc()
        --log("join room suc")
    elseif msgdata.parameter == "quit" then
        logicMgr.LBSManager.QuitRoomSuc()
        --log("quit room suc")
    elseif  msgdata.action == "offline" then
        local msg = decodeJsonStrToTabel(msgdata.messages)
        for k,v in pairs(msg) do
            local m = decodeJsonStrToTabel(v)
            if m and not string.IsNilOrEmpty(m.Message) and m.Message ~="c-i^t-y" then --兼容老账号
                logicMgr.ChatManager.addChatMsg(m)
            end
        end
        logicMgr.ChatManager.LoadAllMsgFromFile()
        logicMgr.ChatManager.HandlePrivateRed()
        return
    end
    --other player quit room
    if msgdata.action == "quit" then
        if logicMgr.LBSManager.IsInRoom(msgdata.Channel) then
            local temp = string.split(msgdata.id,"-")
            if #temp == 3 then
                FireEvent(Config.EventType.CityRoomOtherQuitSuc,temp[3])
            end
        end
    end
    if msgdata.Channel ~= nil then
        if(msgdata.Message=="c-i^t-y")then
            if logicMgr.LBSManager.IsInRoom(msgdata.Channel) then
                if(msgdata.roleId~=logicMgr.HeroManager.GetRoleId())then
                    UICity.getPlayerInCity(3, msgdata);
                    --UICity.buildOtherInCity(msgdata);
                    logicMgr.CityPlayerMgr.AddPlayer(msgdata)
                end
            end
            if msgdata.Channel == Config.MsgChannel.Person then
                if(msgdata.roleId~=logicMgr.HeroManager.GetRoleId())then
                    --UICity.buildOtherInCity(msgdata);
                    logicMgr.CityPlayerMgr.AddPlayer(msgdata)
                end
            end
            return
        end
        if msgdata.Message == "h-e^l-l^o" then
            if msgdata.Channel == Config.MsgChannel.Person and msgdata.roleId ~= logicMgr.HeroManager.GetRoleId() then
                if not logicMgr.FriendManager.IsInBlack(tostring(msgdata.roleId)) then
                    logicMgr.ChatManager.addGetOneHello(msgdata.roleId, msgdata.roleName, msgdata.level);
                    FireEvent(Config.EventType.Fresh_GetOneHello);
                end
            end
            return
        end
        if msgdata.Channel ~= Config.MsgChannel.Person then
            if msgdata.Channel == Config.MsgChannel.System then
                logicMgr.ChatManager.AddMarquee(msgdata.Message)
            else
                if not logicMgr.FriendManager.IsInBlack(tostring(msgdata.roleId)) then
                    logicMgr.ChatManager.addChatMsg(msgdata);
                    logicMgr.ChatManager.ChatPointer(msgdata,msgdata.Channel);
                end
            end
        else
            if not logicMgr.FriendManager.IsInBlack(tostring(msgdata.roleId)) then
                logicMgr.ChatManager.addChatMsg(msgdata);
                logicMgr.ChatManager.ChatPointer(msgdata,msgdata.Channel);
            end
        end
        --FireEvent(Config.EventType.Fresh_Chat,msgdata);
    elseif msgdata.error ~= nil and msgdata.error ~= 0 then
        if msgdata.error == 3 then
            local time = os.date("%Y年%m月%d日%H点%M分",tonumber(msgdata.parameter/1000));
            local msg = "您由于违反了游戏规定被禁言/封号，到"..time.."解禁";
            UISysTips.AddMsg(msg);
        end
    end

end
function chatHandler.CheckIsCityPlayerMsg(msgData)

    if msgData.Message == "c-i^t-y-joinSingle" then
        if msgData.roleId ~= logicMgr.HeroManager.GetRoleId() then
            SDKManager.SendTextMessageByPrivate("c-i^t-y-joinSuc",msgData.roleId)
        end
        return true
    end
    if msgData.Message == "c-i^t-y-joinSuc" then
        if msgData.roleId ~= logicMgr.HeroManager.GetRoleId() then
            logicMgr.CityPlayerMgr.AddPlayer(msgData)
        end
        return true
    end
    if msgData.Message == "c-i^t-y-joinAll" then
        if msgData.roleId ~= logicMgr.HeroManager.GetRoleId() then
            logicMgr.CityPlayerMgr.AddPlayer(msgData)
        end
        return true
    end
    if msgData.Message == "h-e^l-l^o" then
        if msgData.Channel == Config.MsgChannel.Person and msgData.roleId ~= logicMgr.HeroManager.GetRoleId() then
            logicMgr.ChatManager.addGetOneHello(msgData.roleId, msgData.roleName, msgData.emoji);
            FireEvent(Config.EventType.Fresh_GetOneHello);
        end
        return true
    end
    return false
end
--主城玩家小人更新
function chatHandler.SendCityPlayerInfo()
    SDKManager.ReqMyselfUserInfo()
    SDKManager.SendTextMessageByCity("c-i^t-y-joinAll")
end
function chatHandler.SendHello(emoji,playerId,name,pic)
    if IsWindowEditor() then
        local msgtbl = {};
        msgtbl.Channel = Config.MsgChannel.Person;
        msgtbl.Message = "h-e^l-l^o";
        msgtbl.head = logicMgr.HeroManager.GetRoleIcon();
        msgtbl.level = emoji
        msgtbl.roleId = logicMgr.HeroManager.GetRoleId();
        msgtbl.roleName = logicMgr.HeroManager.GetRoleName();
        msgtbl.unRead = true;
        msgtbl.time = HelperFunc.GetServerTime();
        msgtbl.PlayerId = playerId
        msgtbl.PlayerName = name;
        msgtbl.PlayerHead = pic;
        chatHandler.sendPrivateMsg(msgtbl.PlayerId, msgtbl);
    else
        SDKManager.ReqMyselfUserInfo({emoji = emoji})
        SDKManager.SendTextMessageByPrivate("h-e^l-l^o",playerId)
    end
    logicMgr.ChatManager.addSendEmojiId(emoji);
    FireEvent(Config.EventType.RefreshSendEmoji);
end
--聊天室成员信息
function chatHandler.GetChatRoomInfo(json)
    local tb = decodeJsonStrToTabel(json)
    if tb == nil then return end
    for k,v in pairs(tb) do
        if v ~= logicMgr.HeroManager.GetRoleId() then
            SDKManager.SendTextMessageByPrivate("c-i^t-y-joinSingle",v)
        end
    end
end
--[[function chatHandler.addChatPlayer(msgdata)
    G.serverData["chatPlayerList"] = G.serverData["chatPlayerList"] or {};
    local curChatlist = G.serverData["chatPlayerList"];
    for i=1,#curChatlist do
        if tostring(curChatlist[i].PlayerId) == tostring(msgdata.PlayerId) or tostring(curChatlist[i].roleId) == tostring(msgdata.PlayerId) then
            curChatlist[i] = msgdata;
            return;
        end
    end

    table.insert(curChatlist,msgdata);
end]]

--刷新聊天红点
function chatHandler.updateRedPoint()
    G.serverData["chatPlayerList"] = G.serverData["chatPlayerList"] or {};
    if G.serverData["chatPlayerList"] ~= nil and #G.serverData["chatPlayerList"] > 0  then
        for k,v in ipairs(G.serverData["chatPlayerList"]) do
            if v["unRead"] == true then
                UIBattle.isShowRedPoint(true)
                UIChatPanel.isShowRedPoint(true)
            end
        end
    end
end

--屏蔽玩家消息
function chatHandler.sheildFriendsMsg(playerId)
    G.serverData["chat"][curChannel] = G.serverData["chat"][curChannel] or {};
    if G.serverData["chat"][curChannel] ~= nil then
        for k,v in ipairs(G.serverData["chat"][curChannel]) do
            if v["roleId"] == playerId  then
                table.remove(G.serverData["chat"][curChannel],k);
            end
        end
    end

    G.serverData["privateChat"] = G.serverData["privateChat"] or {};
    if G.serverData["privateChat"][playerId] ~= nil then
        for k,v in ipairs(G.serverData["privateChat"][playerId]) do
            if v["PlayerId"] == playerId  then
                table.remove(G.serverData["chat"][curChannel],k);
            end
        end
    end
end
function chatHandler.ResRunLightHandler(msg)
    local runInfo = msg.runInfo
    local id = runInfo.cfgId
    if runInfo.content then
        logicMgr.ChatManager.AddMarquee(runInfo.content)
        return
    end
    local parameter = decodeJsonStrToTabel(runInfo.parameter)
    local cfg = dataTable.getDataTableById("t_systemnotice",id)
    if not cfg then
        logError("找不到配置表 t_systemnotice by id:"..id)
        return
    end
    printTable(parameter)
    local str = ""
    local tb = decodeJsonStrToTabel(cfg.f_Condition)
    local sysStr = ""
    if tb and tb[1]  == EnumConst.MarqueeType.HeroStar then
        local heroModelId = tonumber(parameter.param2)
        local herocfg = dataTable.getDataTableByStringId("t_hero",parameter.param2)
        if herocfg then
            local color = "color10001"
            local colorSys = "color10001"
            local quality = math.floor(herocfg.f_HeroInitialStar/10);
            if quality >= 6 then
                color = "color10002"
                colorSys = "color10002_system"
            end
            str = string.format(getLanguage(cfg.f_Radio),parameter.param1, getLanguage("Sys_Quality"..quality), getLanguage(color),logicMgr.HeroManager.GetHeroNameByModelId(heroModelId))
            sysStr = string.format(getLanguage(cfg.f_Radio.."_system"),parameter.param1, getLanguage("Sys_Quality"..quality), getLanguage(colorSys),logicMgr.HeroManager.GetHeroNameByModelId(heroModelId))
        else
            logError("找不到配置表 t_hero by id:"..parameter.param2)
            return
        end
    else
        str = string.format(getLanguage(cfg.f_Radio), tostring(parameter.param1),tostring(parameter.param2))
        sysStr = string.format(getLanguage(cfg.f_Radio.."_system"), tostring(parameter.param1),tostring(parameter.param2))
        if string.Contains( sysStr,"not have thisKey") then
            sysStr = nil
        end
    end
    logicMgr.ChatManager.AddMarquee(str,sysStr)
end


-------------------------------------------------------
--- 弹幕聊天逻辑
-------------------------------------------------------
---弹幕聊天相关协议
require "proto/stagecomment/message/ReqLevitateCommentMessage"
require "proto/stagecomment/message/ReqGetLevitateCommentInfoMessage" 
---end
-- 发送弹幕请求
function chatHandler.ReqLevitateComment( chatper_id, stage_id, comment ) -- chatper_id 章节id, stage_id 剧情id comment 弹幕内容
    local req = ReqLevitateCommentMessage.New()
    req.chapterId = chatper_id
    req.stageId = stage_id
    req.comment = comment
    sendReqMessage(req)
end
-- 发送弹幕请求返回
function chatHandler.ResLevitateComment( msg )  
    local ui_bullet_chat = CtrlManager.GetCtrl(PanelNames.UIBulletChat)
    if ui_bullet_chat ~= nil then
        ui_bullet_chat.ResLevitateComment()
    end
end

-- -- 拉取弹幕请求
-- function chatHandler.ReqGetLevitateCommentInfo( stage_id ) -- stage_id 剧情id
--     local req = ReqGetLevitateCommentInfoMessage.New();
--     req.stageID = stage_id 
--     sendReqMessage(req)
-- end

-- -- 拉取弹幕返回
-- function chatHandler.ResGetLevitateCommentInfo( msg )
--     local ui_bullet_chat = CtrlManager.GetCtrl(PanelNames.UIBulletChat)
--     if ui_bullet_chat ~= nil then
--         ui_bullet_chat.ResGetLevitateCommentInfo(msg)
--     end
-- end

-- 拉取弹幕请求
function chatHandler.HttpGetLevitateCommentInfo( chapter_id ) -- stage_id 剧情id 
    local url = string.format("%s/%s/%s/CommentList.txt", Config.ServerBulletUrl, Config.GroupId, chapter_id)
    print("HttpGetLevitateCommentInfo url:", url )
    if this.bullet_data == nil then
        this.bullet_data = {}
    end
    if this.bullet_data[chapter_id] == nil then
        Http.Get(url, nil, function(success, cmdStr)
            print("HttpGetLevitateCommentInfo:", success, cmdStr)
            if success then  
                if cmdStr and cmdStr ~= "" then
                    local data_json = decodeJsonStrToTabel(cmdStr)
                    this.bullet_data[tostring(chapter_id)] = data_json 
                    this.ShowLevitateCommentInfo( chapter_id )
                end
            end
        end)
    end
end

function chatHandler.ClearBulletData()
    if this.bullet_data ~= nil then
        this.bullet_data = nil
    end
end

function chatHandler.ShowLevitateCommentInfo( chapter_id )
    if logicMgr.StoryMgr.cur_story_id then
        if Config.OpenCommentAndBullet and logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.BulletChat) then
            local key = logicMgr.HeroManager.GetRoleId().."uistory_switch"
            local story_switch = Util.GetPlayerPrefs(key) 
            if chatHandler.IsOpenBulletFunction() or (story_switch and story_switch == "true") then  
                local net_data = chatHandler.GetLevitateCommentInfo( chapter_id,  logicMgr.StoryMgr.cur_story_id)
                if net_data then
                    chatHandler.PlayNetStoryComment( net_data, logicMgr.StoryMgr.cur_story_id )
                end
            end
        end
    end
end

function chatHandler.GetLevitateCommentInfo( chatper_id, stage_id )
    if this.bullet_data and chatper_id and stage_id then
        chatper_id = tostring(chatper_id) 
        stage_id = tostring(stage_id) 
        if this.bullet_data[ chatper_id ] and this.bullet_data[ chatper_id ][stage_id] then
            return  this.bullet_data[ chatper_id ][ stage_id ]
        end
    end
end

chatHandler.last_play_chapter_id = nil
function chatHandler.PlayNetStoryComment( data, chapter_id ) 
    -- print("chatHandler.PlayNetStoryComment( data, chapter_id ) ----------------------------------", data, chapter_id)
    if data == nil then return end 
    if chatHandler.last_play_chapter_id and chatHandler.last_play_chapter_id == chapter_id then
        return
    end 
    chatHandler.last_play_chapter_id = chapter_id
    local ui_bullet_chat = CtrlManager.GetCtrl(PanelNames.UIBulletChat)
    if ui_bullet_chat ~= nil then
        ui_bullet_chat.PlayNetStoryComment( data )
    end
end

-- 暂停剧情自动播放
function chatHandler.PauseAutoPlay()
    local ui_story = CtrlManager.GetCtrl(PanelNames.UIStory)
    if ui_story ~= nil then
        ui_story.PauseAutoPlay()
    end
end
-- 本地弹幕
function chatHandler.LocalStoryBullet()
    local ui_bullet_chat = CtrlManager.GetCtrl(PanelNames.UIBulletChat)
    if ui_bullet_chat ~= nil then
        ui_bullet_chat.LocalStoryBullet()
    end
end

-- 暂停战斗播放
function chatHandler.PauseBattlePlay()
    local ui_battle_main = CtrlManager.GetCtrl(PanelNames.UIBattleMain)
    if ui_battle_main ~= nil then
        ui_battle_main.PauseBattlePlay()
    end
end

-- 继续战斗播放
function chatHandler.StartBattlePlay()
    local ui_battle_main = CtrlManager.GetCtrl(PanelNames.UIBattleMain)
    if ui_battle_main ~= nil then
        ui_battle_main.StartBattlePlay()
    end
end

-- 读配置是否开启弹幕功能
function chatHandler.IsOpenBulletFunction()
    if chatHandler.is_open_bullet_function ~= nil then
        return chatHandler.is_open_bullet_function 
    else
        local ret = G.dataTable["t_global"][tostring(310)].f_int_value 
        if ret and ret == 0 then
            chatHandler.is_open_bullet_function = false
            return false
        else
            chatHandler.is_open_bullet_function = true
            return true
        end
    end
end
-------------------------------------------------------
--- end
-------------------------------------------------------